package com.ruoyi.project.mahjong.service.impl;

import java.util.*;
import java.util.stream.Collectors;

import cn.hutool.core.util.ObjectUtil;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.framework.redis.RedisCache;
import com.ruoyi.framework.security.LoginUser;
import com.ruoyi.framework.security.service.TokenService;
import com.ruoyi.project.mahjong.domain.*;
import com.ruoyi.project.mahjong.domain.dto.PoolDto;
import com.ruoyi.project.mahjong.domain.enu.PersonState;
import com.ruoyi.project.mahjong.domain.enu.TablenumberState;
import com.ruoyi.project.mahjong.domain.enu.MathDeskState;
import com.ruoyi.project.mahjong.domain.uyil.StreamUtil;
import com.ruoyi.project.mahjong.domain.vo.AutoMateVo;
import com.ruoyi.project.mahjong.mapper.TTablenumberMapper;
import com.ruoyi.project.mahjong.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.project.mahjong.mapper.TablePoolMapper;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServlet;

/**
 * 陪桌数据池Service业务层处理
 *
 * @author ruoyi
 * @date 2023-07-25
 */
@Service
public class TablePoolServiceImpl implements ITablePoolService {
    @Autowired
    private TablePoolMapper tablePoolMapper;

    @Autowired
    private IDeskIngService deskIngService;
    @Autowired
    private IDeskMemberService deskMemberService;
    @Autowired
    private ITMemberService tMemberService;
    @Autowired
    private TTablenumberMapper tTablenumberMapper;
    @Autowired
    private ITTablenumberService tTablenumberService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private RedisCache redisCache;

    /**
     * 查询陪桌数据池
     *
     * @param id 陪桌数据池ID
     * @return 陪桌数据池
     */
    @Override
    public TablePool selectTablePoolById(Long id) {
        return tablePoolMapper.selectTablePoolById(id);
    }

    /**
     * 查询陪桌数据池列表
     *
     * @param tablePool 陪桌数据池
     * @return 陪桌数据池
     */
    @Override
    public List<TablePool> selectTablePoolList(TablePool tablePool) {
        List<TablePool> tablePools = tablePoolMapper.selectTablePoolList(tablePool);
  /*  tablePools.stream().
               forEach(bak3 ->  bak3.setMode(bak3.getBak3()));
        tablePools.stream().
                forEach(bak3 ->  bak3.setIntegral(bak3.getBak2()));
        tablePools.stream().
                forEach(bak3 ->  bak3.setReservationTime(bak3.getBak1()));*/
        return tablePools;
    }

    /**
     * 新增陪桌数据池
     *
     * @param tablePool 陪桌数据池
     * @return 结果
     */
    @Override
    public int insertTablePool(TablePool tablePool) throws Exception {
        tablePool.setCreateTime(DateUtils.getNowDate());

       /* if(ObjectUtil.isNotNull(tablePool.getDeskNumber())){
            DeskMember deskMember=new DeskMember();
            deskMember.setMemberId(tablePool.getMemberId());
            List<DeskMember> deskMemberList=deskMemberService.selectDeskMemberList(deskMember);
            DeskIng deskIng=new DeskIng();
            deskIng.setDeskId(tablePool.getDeskNumber());
            List<DeskIng> deskIngList= deskIngService.selectDeskIngList(deskIng);
            if(ObjectUtil.isNotEmpty(deskIngList)){
                deskIng=deskIngList.get(0);
            }else{
                deskIngService.insertDeskIng(deskIng);
            }
            if(ObjectUtil.isNotEmpty(deskMemberList)){


                DeskMember deskMember1=  deskMemberList.get(0);
                //如果该人员已成局以后得状态，则不允许被修改
                if(deskMember1.getState().equals(MyConstat.NO_CHEGN_JU)){
                    deskMember1.setDeskId(deskIng.getId());
                    deskMemberService.updateDeskMember(deskMember1);
                }else{
                    throw new Exception("该人员已成局或者已开始，不允许修改桌号");
                }

            }
            deskMember.setDeskId(deskIng.getId());
            deskMember.setState("0");
            deskMemberService.insertDeskMember(deskMember);

        }*/
        TMember tMember = tMemberService.selectTMemberById(tablePool.getMemberId());
         tablePool.setMemberName(tMember.getName());
         tablePool.setBak2(tablePool.getIntegral());
         tablePool.setBak3(tablePool.getMode());
         tablePool.setBak1(tablePool.getReservationTime());
        return tablePoolMapper.insertTablePool(tablePool);
    }

    /**
     * 修改陪桌数据池
     *
     * @param tablePool 陪桌数据池
     * @return 结果
     */
    @Override
    public int updateTablePool(TablePool tablePool) throws Exception {
        tablePool.setUpdateTime(DateUtils.getNowDate());
       /* if(ObjectUtil.isNotNull(tablePool.getDeskNumber())){
            DeskMember deskMember=new DeskMember();
            deskMember.setMemberId(tablePool.getMemberId());
            deskMember.setBak3(MyConstat.DESK_ING);
            List<DeskMember> deskMemberList=deskMemberService.selectDeskMemberList(deskMember);
            if(ObjectUtil.isNotEmpty(deskMemberList)){
                DeskMember deskMember1=  deskMemberList.get(0);
                //如果该人员已成局以后得状态，则不允许被修改
                DeskIng deskIng=new DeskIng();
                deskIng.setDeskId(tablePool.getDeskNumber());
                deskIng.setStatus(MyConstat.NO_CHEGN_JU);
                List<DeskIng> deskIngList= deskIngService.selectDeskIngList(deskIng);
                if(ObjectUtil.isNotEmpty(deskIngList)){
                    deskIng=deskIngList.get(0);
                }else{
                    deskIngService.insertDeskIng(deskIng);
                }
                if(deskMember1.getState().equals(MyConstat.NO_CHEGN_JU)){
                    deskMember1.setDeskId(deskIng.getId());
                  *//*  deskMember1.setDeskId(tablePool.getDeskNumber());*//*
                    deskMemberService.updateDeskMember(deskMember1);
                }else{
                    throw new Exception("该人员已成局或者已开始，不允许修改桌号");
                }

            }else{
                DeskIng deskIng=new DeskIng();
                deskIng.setDeskId(tablePool.getDeskNumber());
               List<DeskIng> deskIngList= deskIngService.selectDeskIngList(deskIng);
                if(ObjectUtil.isNotEmpty(deskIngList)){
                    deskIng=deskIngList.get(0);
                }else{
                    deskIngService.insertDeskIng(deskIng);
                }
                deskMember.setDeskId(deskIng.getId());
                deskMember.setState(MyConstat.NO_CHEGN_JU);
                deskMemberService.insertDeskMember(deskMember);

            }

        }*/

        return tablePoolMapper.updateTablePool(tablePool);
    }

    /**
     * 批量删除陪桌数据池
     *
     * @param ids 需要删除的陪桌数据池ID
     * @return 结果
     */
    @Override
    public int deleteTablePoolByIds(Long[] ids) {

        return tablePoolMapper.deleteTablePoolByIds(ids);
    }

    /**
     * 删除陪桌数据池信息
     *
     * @param id 陪桌数据池ID
     * @return 结果
     */
    @Override
    public int deleteTablePoolById(Long id) {
        return tablePoolMapper.deleteTablePoolById(id);
    }

    @Override
    public Map<String, Object> selectdetails(PoolDto dto) {
        Map<String, Object> result = new HashMap<>();
        List<TMember> memberList = new LinkedList<>();
        if (ObjectUtil.isNotNull(dto.getDeskId())) {
            TTablenumber tTablenumber = tTablenumberMapper.selectTTablenumberById(dto.getDeskId());

            DeskIng ing = new DeskIng();
            ing.setDeskId(dto.getDeskId());
            //设置为进行中
            ing.setBak2(MyConstat.DESK_ING);
            if (tTablenumber.getStatus().equals(TablenumberState.NO_LOCK.getValue())) {
                ing.setStatus(MathDeskState.DP.getValue());
                ing.setBak2(MyConstat.DESK_ING);
                deskIngService.insertDeskIng(ing);
                result.put("desk", ing);
                tTablenumber.setStatus(TablenumberState.LOCK.getValue());
                tTablenumberMapper.updateTTablenumber(tTablenumber);
            } else {
                List<DeskIng> deskIngList = deskIngService.selectDeskIngList(ing);
                if (ObjectUtil.isNotEmpty(deskIngList)) {
                    result.put("desk", deskIngList.get(0));
                }
            }


        }
        //加载原有桌面信息
        if (ObjectUtil.isNotNull(dto.getDeskId())) {
            TablePool myPool = new TablePool();
            myPool.setDeskNumber(dto.getDeskId());
            List<TablePool> poolList = tablePoolMapper.selectTablePoolList(myPool);
            for (TablePool pool : poolList) {
                TMember member = tMemberService.selectTMemberById(pool.getMemberId());

                if (ObjectUtil.isNotNull(member)){member.setMode(pool.getMode());
                member.setIntegral(pool.getIntegral());
                memberList.add(member);}
            }
        }
        //加载新增的桌面信息
        if (ObjectUtil.isNotNull(dto.getId())) {
            TablePool pool = selectTablePoolById(dto.getId());
            TMember member = tMemberService.selectTMemberById(pool.getMemberId());
            if (ObjectUtil.isNotNull(member)){
            member.setMode(pool.getMode());
            member.setIntegral(pool.getIntegral());
            memberList.add(member);}
        }

        List<TMember> newList2 = memberList.stream().collect(Collectors
                .collectingAndThen(
                        Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(TMember::getId))),
                        ArrayList::new));
        memberList.removeAll(Collections.singleton(null));
    //   newList2.get(0).setSource("0");
      // newList2.get(0).setCount("2");
     //  newList2.get(0).setMode("common");
//        desk.setSource("0");
//        desk.setCount("2");
//        desk.setMode("common");
//        newList2.add(0,desk);
        result.put("details", newList2);
        return result;
    }

    /**
     * 配桌
     *
     * @param dto
     */
    @Override
    public void match(PoolDto dto) {
        if (ObjectUtil.isNotNull(dto.getId())) {
            TablePool pool = selectTablePoolById(dto.getId());
            pool.setState(MyConstat.PZ);
            pool.setDeskNumber(dto.getDeskId());
            try {
                updateTablePool(pool);
            } catch (Exception e) {
                e.printStackTrace();
            }
          /*  DeskIng ing = new DeskIng();
            ing.setDeskId(dto.getDeskId());
            ing.setStatus(MyConstat.DESK_ING);
            List<DeskIng> deskIngList = deskIngService.selectDeskIngList(ing);
            if (ObjectUtil.isNotEmpty(deskIngList)) {
               ing= deskIngList.get(0);
                ing.setBak1(String.valueOf(Long.valueOf(ing.getBak1()) + 1));
                deskIngService.updateDeskIng(ing);
            }else {
                deskIngService.insertDeskIng(ing);
            }
                DeskMember deskMember=new DeskMember();
                deskMember.setMemberId(pool.getMemberId());
                deskMember.setDeskId(ing.getId());
                List<DeskMember> deskMemberList=deskMemberService.selectDeskMemberList(deskMember);
                if(ObjectUtil.isNotEmpty(deskMemberList)){
                    deskMember=deskMemberList.get(0);
                    deskMember.setDeskId(ing.getId());
                    deskMember.setMemberId(pool.getMemberId());
                    deskMemberService.updateDeskMember(deskMember);
                }else{
                    deskMember.setDeskId(ing.getId());
                    deskMember.setMemberId(pool.getMemberId());
                    deskMemberService.insertDeskMember(deskMember);
                }

            }*/
        }

    }

    /**
     * 成局
     *
     * @param dto
     */
    @Override
    @Transactional
    public void chengju(PoolDto dto) {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());


        if (ObjectUtil.isNotNull(dto.getId())) {
//            根据开桌情况id找到开桌情况
            DeskIng ing = deskIngService.selectDeskIngById(dto.getDeskId());
            DeskIng ing1=new DeskIng();
            ing1.setStatus(MathDeskState.CJ.getValue());
            ing1.setBak2(MyConstat.DESK_ING);
            ing1.setUpdateTime(DateUtils.getNowDate());
            ing1.setUserId(loginUser.getUser().getUserId());
            ing1.setId(ing.getId());
            ing1.setUpdateBy(loginUser.getUsername());
            deskIngService.updateDeskIng(ing1);
//           修改配卓池数据
            TablePool pool = selectTablePoolById(dto.getId());
            pool.setDeskNumber(ing.getDeskId());
//            设置已排桌
            pool.setState(MyConstat.PZ);

            try {
                updateTablePool(pool);
                updateTablePoolByDeskId(pool);
            } catch (Exception e) {
                e.printStackTrace();
            }

              pool = new TablePool();
//            找到此桌人员信息
            pool.setDeskNumber(ing.getDeskId());
            List<TablePool> tablePoolList = tablePoolMapper.selectTablePoolList(pool);

            for (TablePool mypool : tablePoolList) {
                 mypool.setIsState("1");
                 mypool.setDeskNumber(ing.getDeskId());
                 tablePoolMapper.updateTablePool(mypool);
                DeskMember deskMember = new DeskMember();
                deskMember.setMemberId(mypool.getMemberId());
                TMember tMember = tMemberService.selectTMemberById(mypool.getMemberId());
                if (ObjectUtil.isNotNull(tMember)){
                    deskMember.setMemberName(tMember.getName());
//                deskMember.setMemberName(tMemberService.selectTMemberById(mypool.getMemberId()).getName());
                deskMember.setDeskId(ing.getId());
                deskMember.setState(PersonState.AP.getValue());
                deskMemberService.insertDeskMember(deskMember);}
            }
            TTablenumber tTablenumber = new TTablenumber();
            tTablenumber.setStatus(TablenumberState.CHENGJU.getValue());
            tTablenumber.setId(ing.getDeskId());
            tTablenumberMapper.updateTTablenumber(tTablenumber);

            goStart(ing.getDeskId());

//            2023//11/15 新增



          /*  //最后一人
            DeskMember deskMember=new DeskMember();
            deskMember.setMemberId(pool.getMemberId());
            deskMember.setMemberName(member.getName());
            deskMember.setDeskId(ing.getId());
            deskMember.setState(PersonState.AP.getValue());
            deskMemberService.insertDeskMember(deskMember);*/

        }
    }

    private void updateTablePoolByDeskId(TablePool pool) {

        tablePoolMapper.updateTablePoolByDeskId(pool);
    }

    /**
     * 检查该会员是否在待排数据池
     *
     * @param tablePool
     * @return
     */
    @Override
    public int checkMember(TablePool tablePool) {
        TablePool check = new TablePool();
        check.setMemberId(tablePool.getMemberId());
        List<TablePool> tablePoolList = selectTablePoolList(check);
        return tablePoolList.size();
    }

    @Override
    public void deleteTablePoolByMemberId(Long memberId) {
        tablePoolMapper.deleteTablePoolByMemberId(memberId);
    }

    @Override
    public void updateTablePoolByMemberId(TablePool tablePool) {
        tablePoolMapper.updateTablePoolByMemberId(tablePool);
    }

    @Override
    public Long selectAutoMate(PoolDto dto) {
//        查出当前用户积分模式，不同桌
        AutoMateVo autoMateVo = tablePoolMapper.selectAutoMate(dto);
        List<Long> longs=new ArrayList<>() ;
//        根据模式积分，不同桌匹配
        try {
            longs =tablePoolMapper.selectAllLikes(autoMateVo);
        }catch (Exception exception){
            System.out.println("匹配错误");
        }

//        返回出合适桌号
        if (ObjectUtil.isNotEmpty(longs) && longs.size()!=0) {
            Long aLong = longs.get(0);
            return aLong;
        }
//        没找到合适的，就随便返回一个桌号

        TTablenumber tTablenumber=new TTablenumber();
        tTablenumber.setStatus("0");
        List<TTablenumber> list = tTablenumberService.selectTTablenumberList(tTablenumber);
        if (ObjectUtil.isNotEmpty(list) && list.size() != 0 && list.get(0).getId()!=null) {
            return list.get(0).getId();
        } else {
            return 1L;
        }
    }

    /**
     * 开局
     * @param id
     */
    @Override
    public void goStart(Long id) {
        tablePoolMapper.goStart(id);
    }

    @Override
    public List<TablePool> selectTablePoolListmy(TablePool tablePool) {
        List<TablePool> tablePools =  tablePoolMapper.selectTablePoolListmy( tablePool);
        return tablePools;
    }

    @Override
    public void updateTablePoolmy(Long memberId) {
        tablePoolMapper.updateTablePoolmy(memberId);
    }
}
